package com.sanjiahantang.youjiaclient.module.cases.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseBean;
import com.sanjiahantang.youjiaclient.base.BaseMvpPresenter;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.module.cases.beans.CaseBean;
import com.sanjiahantang.youjiaclient.module.cases.beans.DesignerBean;
import com.sanjiahantang.youjiaclient.module.cases.models.ICaseModel;
import com.sanjiahantang.youjiaclient.module.cases.models.impl.CaseModel;
import com.sanjiahantang.youjiaclient.module.cases.views.CaseView;
import com.sanjiahantang.youjiaclient.module.cases.views.impl.CaseDetailActivity;
import com.sanjiahantang.youjiaclient.module.cases.views.impl.DesignerDetailActivity;
import com.sanjiahantang.youjiaclient.module.common.beans.ConditionBean;
import com.sanjiahantang.youjiaclient.module.common.views.impl.SearchActivity;
import com.sanjiahantang.youjiaclient.module.evaluate.beans.EvaServiceBean;
import com.sanjiahantang.youjiaclient.module.goods.models.IGoodsModel;
import com.sanjiahantang.youjiaclient.module.goods.models.impl.GoodsModel;
import com.sanjiahantang.youjiaclient.module.me.favorite.views.FavoriteCaseView;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.sanjiahantang.youjiaclient.utils.SPUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zy on 2017/8/25.
 */

public class CasePresenter extends BaseMvpPresenter<CaseView> {

    private List<ConditionBean.SelectorData> styleList, roomTypeList, priceList;
    private List<ConditionBean.AddressData> addressList;
    private ICaseModel caseModel;
    private IGoodsModel goodsModel;
    private QuickAdapter selectorAdapter, caseAdapter, detailAdapter, addressAdapter;
    private String currentStyle, currentDoor, currentPrice, currentAddress;
    private String keyWords;
    private CaseView.DetailCallBack detailCallBack;
    private HashMap<String, Integer> DETAIL_RES_DIC;
    private HashMap<String, String> DETAIL_TITLE_DIC;

    public void setOnListLoadListener(Context context, CaseView.OnListLoadListener onListLoadListener) {
        this.onListLoadListener = onListLoadListener;
        selectorAdapter = new QuickAdapter<ConditionBean.SelectorData>(context, R.layout.item_text) {
            @Override
            protected void convert(BaseAdapterHelper helper, final ConditionBean.SelectorData item) {
                helper.setText(R.id.text1, item.getName());
                helper.getView().setBackgroundColor(Color.WHITE);
                helper.setOnClickListener(R.id.text1, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (CaseView.KEY_TYPES[0].equals(item.getParentId())) {
                            currentStyle = item.getDicValue();
                        } else if (CaseView.KEY_TYPES[1].equals(item.getParentId())) {
                            currentDoor = item.getDicValue();
                        } else if (CaseView.KEY_TYPES[2].equals(item.getParentId())) {
                            currentPrice = item.getDicValue();
                        }
                        loadCases(context, keyWords);
                        CasePresenter.this.onListLoadListener.recoverDefault();
                        CasePresenter.this.onListLoadListener.setTextSelected(item.getParentId(), item.getDicName(), item.getDicValue());
                    }
                });
            }
        };

        addressAdapter = new QuickAdapter<ConditionBean.AddressData>(context, R.layout.item_text) {
            @Override
            protected void convert(BaseAdapterHelper helper, final ConditionBean.AddressData item) {
                String city = item.getAddress();
                if (!TextUtils.isEmpty(city) && city.indexOf("市") > -1) {
                    city = city.substring(0, city.length() - 1);
                }
                helper.setText(R.id.text1, city);
                helper.getView().setBackgroundColor(Color.WHITE);
                helper.setOnClickListener(R.id.text1, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        currentAddress = item.getAddress();
                        if ("全部".equals(currentAddress)) {
                            currentAddress = null;
                        }
                        loadCases(context, keyWords);
                        CasePresenter.this.onListLoadListener.recoverDefault();
                        CasePresenter.this.onListLoadListener.setTextSelected(CaseView.KEY_TYPES[3], item.getAddress(), item.getAddress());
                    }
                });
            }
        };

        caseAdapter = new QuickAdapter<CaseBean.Item>(context, R.layout.item_case_list) {
            @Override
            protected void convert(BaseAdapterHelper helper, final CaseBean.Item item) {
                ImageView ivCaseMain = helper.getView(R.id.ivCaseMain);
                Picasso.with(context).load(FileUtils.rePath(item.getCaseImg())).placeholder(R.drawable.i_match).error(R.drawable.i_match).into(ivCaseMain);


                ImageView iv_case_collect = helper.getView(R.id.iv_case_collect);
                if (item.getState() == 1) {
                    iv_case_collect.setImageResource(R.drawable.i_heart_on);
                } else {
                    iv_case_collect.setImageResource(R.drawable.i_heart_white);
                }

                helper.setVisible(R.id.txtCaseTitle, false);
                helper.setText(R.id.tv_case_detail, item.getDoor() + " , " + item.getStyle());
                helper.setText(R.id.tv_case_collectnum, String.valueOf(item.getCollectNumber()));

                helper.getView().setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, CaseDetailActivity.class);
                        intent.putExtra(KEY_ID, item.getId());
                        context.startActivity(intent);
                    }
                });

                if (item.getState() == 1) {
                    iv_case_collect.setImageResource(R.drawable.i_heart_on);
                    iv_case_collect.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Utils.showDialog((Activity) context, "提示", "确定取消收藏吗？", "", "", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Utils.dismissDialog();
                                    switch (view.getId()) {
                                        case com.sanjiahantang.uilibrary.R.id.txtDialogCancel:
                                            break;
                                        case com.sanjiahantang.uilibrary.R.id.txtDialogSure:
                                            deleteCollectInfo(context, item.getId());
                                            break;
                                    }
                                }
                            });
                        }
                    });
                } else {
                    iv_case_collect.setImageResource(R.drawable.i_heart_white);
                    iv_case_collect.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            addCollectInfo(context, item.getId());
                        }
                    });
                }

            }
        };
        onListLoadListener.initContainers(selectorAdapter, caseAdapter, addressAdapter);
    }

    public void deleteCollectInfo(final Context context, int id) {
        mView.showProgress();
        Map<String, Object> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put(FavoriteCaseView.KEY_ROLE_TYPE, 0);
        param.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        param.put(KEY_TYPE, 1);
        param.put(FavoriteCaseView.KEY_FAVORITE_ID, id);
        caseModel.deleteCollectInfo(context, param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                loadCases(context, keyWords);
            }

            @Override
            public void onFailure(String message) {
            }
        });
    }

    public void addCollectInfo(final Context context, int id) {
        mView.showProgress();
        Map<String, Object> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put(FavoriteCaseView.KEY_ROLE_TYPE, 0);
        param.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        param.put(KEY_TYPE, 1);
        param.put(FavoriteCaseView.KEY_FAVORITE_ID, id);
        caseModel.addCollectInfo(context, param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                loadCases(context, keyWords);
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    private CaseView.OnListLoadListener onListLoadListener;

    public CasePresenter() {
        caseModel = new CaseModel();
        goodsModel = new GoodsModel();
        styleList = new ArrayList<>();
        roomTypeList = new ArrayList<>();
        priceList = new ArrayList<>();
        addressList = new ArrayList<>();
        currentStyle = "";
        currentDoor = "";
        currentPrice = "";
        currentAddress = "";
        DETAIL_RES_DIC = new HashMap<>();
        DETAIL_TITLE_DIC = new HashMap<>();
        for (int i = 0; i < CaseView.KEY_IMAGE_IDS.length; i++) {
            DETAIL_RES_DIC.put(CaseView.KEY_IMAGE_IDS[i], CaseView.IMAGE_RES_IDS[i]);
            DETAIL_TITLE_DIC.put(CaseView.KEY_IMAGE_IDS[i], CaseView.IMAGE_TITLES[i]);
        }
    }

    public void loadCases(Context context, String keyWords) {
        this.keyWords = keyWords;
        Map<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(KEY_PAGE, 0);
        params.put(KEY_PAGE_SIZE, DEFAULT_PAGE_SIZE);
        Map<String, String> map = new HashMap<>();
        map.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        if (TextUtils.isEmpty(currentStyle)) {
            map.put(CaseView.KEY_TYPES[0], "");
        } else {
            map.put(CaseView.KEY_TYPES[0], currentStyle);
        }

        if (TextUtils.isEmpty(currentDoor)) {
            map.put(CaseView.KEY_TYPES[1], "");
        } else {
            map.put(CaseView.KEY_TYPES[1], currentDoor);
        }

        if (TextUtils.isEmpty(currentPrice)) {
            map.put(CaseView.KEY_TYPES[2], "");
        } else {
            map.put(CaseView.KEY_TYPES[2], currentPrice);
        }
        if (TextUtils.isEmpty(currentAddress)) {
            map.put(CaseView.KEY_TYPES[3], "");
        } else {
            map.put(CaseView.KEY_TYPES[3], currentAddress);
        }

        map.put(CaseView.KEY_CASE_TITLE, keyWords);
        params.put(KEY_PARAM, map);
        mView.showProgress();
        caseModel.loadCaseByCondition(context, params, new CaseCallBack());
    }

    public void loadSelectors(Context context, int type) {
        mView.showProgress();
        Map<String, String> param = new HashMap<>();
        if (type == CaseView.TYPE_ADDRESS) {
            param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        } else {
            param.put(CaseView.KEY_PARENT_ID, CaseView.KEY_TYPES[type]);
        }
        caseModel.loadSelectors(context, param, new ConditionCallBack(), type);
    }


    public void resetAdapterData(Context context, int type) {
        ConditionBean.SelectorData allData = new ConditionBean.SelectorData();
        allData.setDicName("全部");
        if (type == CaseView.TYPE_ADDRESS) {
            addressAdapter.clear();
        } else {
            selectorAdapter.clear();
        }

        switch (type) {
            case CaseView.TYPE_STYLE:
                if (styleList.size() == 0) {
                    loadSelectors(context, type);
                } else {
                    allData.setParentId(CaseView.KEY_TYPES[0]);
                    selectorAdapter.add(allData);
                    selectorAdapter.addAll(styleList);
                }

                break;
            case CaseView.TYPE_ROOM_TYPE:
                if (roomTypeList.size() == 0) {
                    loadSelectors(context, type);
                } else {
                    allData.setParentId(CaseView.KEY_TYPES[1]);
                    selectorAdapter.add(allData);
                    selectorAdapter.addAll(roomTypeList);
                }

                break;
            case CaseView.TYPE_PRICE:
                if (priceList.size() == 0) {
                    loadSelectors(context, type);
                } else {
                    allData.setParentId(CaseView.KEY_TYPES[2]);
                    selectorAdapter.add(allData);
                    selectorAdapter.addAll(priceList);
                }

                break;
            case CaseView.TYPE_ADDRESS:
                if (addressList.size() == 0) {
                    loadSelectors(context, type);
                } else {
                    ConditionBean.AddressData addressData = new ConditionBean.AddressData();
                    addressData.setAddress("全部");
                    addressAdapter.add(addressData);
                    addressAdapter.addAll(addressList);
                }

                break;
        }
    }

    public void loadCaseById(Context context, long id) {

        if (detailAdapter == null) {
            detailAdapter = new QuickAdapter<CaseBean.Image>(context, R.layout.item_case_info) {
                @Override
                protected void convert(BaseAdapterHelper helper, CaseBean.Image item) {
                    ImageView ivIcon = helper.getView(R.id.ivIcon);
                    ivIcon.setImageResource(item.getImageSmall());
                    helper.setText(R.id.txtName, DETAIL_TITLE_DIC.get(item.getGroupId()));
                    ImageView ivPhoto = helper.getView(R.id.ivPhoto);

                    Picasso.with(context).load(FileUtils.rePath(item.getUrl())).placeholder(R.drawable.i_head_default).into(ivPhoto);
                }
            };
            this.detailCallBack.initAdapter(detailAdapter);
        }
        Map<String, Object> param = new HashMap<>();
        if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
            param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        }
        String phone = SPUtils.get(context, SPConfig.PHONE, "").toString();
        if (!TextUtils.isEmpty(phone)) {
            param.put(KEY_PHONE, phone);
        } else {
            param.put(KEY_PHONE, "");
        }
        param.put(KEY_ID, id);
        mView.showProgress();
        caseModel.loadCaseById(context, param, new LoadCaseByIdCallBack());
    }

    public void goSearchPage(Activity activity) {
        Intent intent = new Intent(activity, SearchActivity.class);
        intent.putExtra(KEY_TYPE, SEARCH_TYPE_CASE);
        activity.startActivityForResult(intent, BaseView.INTENT_CASE);
    }

    public void setDetailCallBack(CaseView.DetailCallBack detailCallBack) {
        this.detailCallBack = detailCallBack;
    }

    public void loadDesignerInfo(Context context, String phone, final BaseView.OnLoadListener listener) {
        Map<String, String> param = new HashMap<>();
        if (ConfigValue.DATA_KEY != null) {
            param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        } else {
            param.put(KEY_TOKEN, "");
        }
        mView.showProgress();
        param.put(KEY_PHONE, phone);
        caseModel.loadDesignerInfo(context, param, new CallBack<DesignerBean>() {
            @Override
            public void onSuccess(DesignerBean response, Context context, Object tag) {
                if (mView == null) return;

                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    listener.onLoad(response.getData());
                } else {
                    hideProgress();
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                hideProgress();
            }
        });
    }

    public void searchCaseInfo(Context context, String phone, final BaseView.OnLoadListener listener) {
        Map<String, Object> param = new HashMap<>();
        if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
            param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        }
        param.put(KEY_PAGE, 0);
        param.put(KEY_PAGE_SIZE, DEFAULT_PAGE_SIZE);
        Map<String, String> map = new HashMap<>();
        map.put(CaseView.KEY_DESIGNER_PHONE, phone);
        String cusPhone = SPUtils.get(context, SPConfig.PHONE, "").toString();
        if (!TextUtils.isEmpty(cusPhone)) {
            map.put(KEY_PHONE, cusPhone);
        }
        param.put(KEY_PARAM, map);
        caseModel.loadCaseByCondition(context, param, new CallBack<CaseBean>() {
            @Override
            public void onSuccess(CaseBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC) {
                    listener.onLoad(response.getData());
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });

    }

    public void searchDesignAllAppraisePhone(Context context, String phone, final BaseView.OnLoadListener listener) {
        Map<String, Object> param = new HashMap<>();
        if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
            param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        }
        param.put(KEY_PAGE, 0);
        param.put(KEY_PAGE_SIZE, DEFAULT_PAGE_SIZE);
        Map<String, String> map = new HashMap<>();
        map.put(CaseView.KEY_ROLE_PHONE, phone);
        param.put(KEY_PARAM, map);
        goodsModel.searchDesignAllAppraisePhone(context, param, new CallBack<EvaServiceBean>() {
            @Override
            public void onSuccess(EvaServiceBean response, Context context, Object tag) {
                if (response.getCode() == RESPONSE_CODE_SUC) {
                    listener.onLoad(response.getData());
                }
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    public void saveSelBidRequireInfoForCustomer(final Context context, final int requireId, String phone, final BaseView.OnLoadListener listener) {
        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put("ucriId", String.valueOf(requireId));
        param.put(KEY_PHONE, phone);
        if (mView == null) return;
        mView.showProgress();
        caseModel.saveSelBidRequireInfoForCustomer(context, param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC){
                    listener.onLoad(null);
                }else{
                    Utils.showToast(context,"选择设计师失败");
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context,"选择设计师失败");
            }
        });
    }


    private class ConditionCallBack implements CallBack<ConditionBean> {

        @Override
        public void onSuccess(ConditionBean response, Context context, Object tag) {
            hideProgress();
            if (response == null || response.getCode() == RESPONSE_CODE_FAIL || response.getCode() == RESPONSE_CODE_TIME_OUT) {
                return;
            }

            ConditionBean.SelectorData allData = new ConditionBean.SelectorData();

            allData.setDicName("全部");
            if (tag instanceof Integer) {
                switch ((int) tag) {
                    case CaseView.TYPE_STYLE:
                        styleList.clear();
                        styleList.addAll(response.getData());
                        allData.setParentId(CaseView.KEY_TYPES[0]);
                        break;
                    case CaseView.TYPE_ROOM_TYPE:
                        roomTypeList.clear();
                        roomTypeList.addAll(response.getData());
                        allData.setParentId(CaseView.KEY_TYPES[1]);
                        break;
                    case CaseView.TYPE_PRICE:
                        priceList.clear();
                        priceList.addAll(response.getData());
                        allData.setParentId(CaseView.KEY_TYPES[2]);
                        break;
                    case CaseView.TYPE_ADDRESS:
                        addressList.clear();
                        addressList.addAll(response.getAddressData());
                        break;
                }
            }

            if ((int) tag == CaseView.TYPE_ADDRESS) {
                addressAdapter.clear();
                ConditionBean.AddressData addressData = new ConditionBean.AddressData();
                addressData.setAddress("全部");
                addressAdapter.add(addressData);
                addressAdapter.addAll(response.getAddressData());
            } else {
                selectorAdapter.clear();
                selectorAdapter.add(allData);
                selectorAdapter.addAll(response.getData());
            }

        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }


    private class CaseCallBack implements CallBack<CaseBean> {

        @Override
        public void onSuccess(CaseBean response, Context context, Object tag) {
            hideProgress();
            if (caseAdapter != null) {
                caseAdapter.clear();
            }
            CaseBean.Data data = response.getData();
            if (caseAdapter != null && data != null && data.getList() != null) {
                caseAdapter.addAll(data.getList());
            }
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }

    private class LoadCaseByIdCallBack implements CallBack<CaseBean.DetailBean> {
        @Override
        public void onSuccess(CaseBean.DetailBean response, Context context, Object tag) {
            hideProgress();
            List<CaseBean.Image> images = new ArrayList<>();
            CaseBean.Detail data = response.getData();
            if (response != null && response.getData() != null) {
                if (response.getData().getCaseImg() != null) {
                    String urlDefault = null;
                    for (int i = 0, max = response.getData().getCaseImg().size(); i < max; i++) {
                        CaseBean.Image respImage = response.getData().getCaseImg().get(i);
                        if (DETAIL_RES_DIC.containsKey(respImage.getGroupId())) {
                            CaseBean.Image image = new CaseBean.Image();
                            image.setUrl(respImage.getUrl());
                            image.setGroupId(respImage.getGroupId());
                            image.setImageSmall(DETAIL_RES_DIC.get(image.getGroupId()));
                            images.add(image);
                        } else if (TextUtils.equals(CaseView.URL_IMG_DEFAULT,respImage.getGroupId())) {
                            urlDefault = respImage.getUrl();
                        } else if (TextUtils.equals(CaseView.URL_VIDEO,respImage.getGroupId())){
                            data.setIndexVideo(respImage.getUrl());
                        }
                    }

                    if (urlDefault != null) {
                        data.setUrlDefault(urlDefault);
                    }
                }

                detailAdapter.clear();
                detailAdapter.addAll(images);
                detailCallBack.loadData(data);
            }

        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }

    private void hideProgress() {
        if (mView != null) {
            mView.hideProgress();
        }
    }
}
